package com.aube.plugin.detail;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.text.Html;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.Utils;

public class EllipsizingTextView extends TextView{
    private  String ELLIPSIS = "... ";
    private  String ELLIPSISADD = "...";

    private int maxLines = -1;
    private float lineSpacingMultiplier = 1.0f;
    private float lineAdditionalVerticalPadding = 0.0f;
    private Context mContext;

    private boolean isWala = true;

    public EllipsizingTextView(Context context) {
        this(context, null);
    }
    public EllipsizingTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public EllipsizingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    @Override
    public void setMaxLines(int maxLines) {
        super.setMaxLines(maxLines);
        this.maxLines = maxLines;
    }

    public void setReadUp(boolean isWala) {
        ELLIPSIS = "...    . " ;
        ELLIPSISADD = "...    .";
        this.isWala = isWala;
    }

    public int getMaxLines() {
        return maxLines;
    }

    @Override
    public void setLineSpacing(float add, float mult) {
        this.lineAdditionalVerticalPadding = add;
        this.lineSpacingMultiplier = mult;
        super.setLineSpacing(add, mult);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        resetTextWithDefaultLine(maxLines);
        super.onDraw(canvas);
    }

    private void resetTextWithDefaultLine(int maxLines){
        String fullText = getText().toString();
        if (StringUtils.isNotBlank(fullText) && getLineCount() <= maxLines ) return;
        String workingText = fullText;
        if (maxLines != -1) {
            Layout layout = createWorkingLayout(workingText);
            if (layout.getLineCount() > maxLines) {
                workingText = fullText.substring(0, layout.getLineEnd(maxLines - 1)).trim();
                while (createWorkingLayout(workingText + ELLIPSIS).getLineCount() > maxLines) {
                    int lastSpace = workingText.length() - 1;
                    if (lastSpace == -1) {
                        break;
                    }
                    workingText = workingText.substring(0, lastSpace);
                }
                int lastBracketIndex = workingText.lastIndexOf('[');
                if (lastBracketIndex >= workingText.length() - 5) {
                    try {
                        workingText = workingText.substring(0, lastBracketIndex);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                workingText = workingText + ELLIPSISADD;
            }
        }
        if (!workingText.equals(getText())) {
            try {
                if (isWala) {
                    setText(TextContentTool.getSpanContent(workingText));
                } else {
                    if (StringUtils.isNotBlank(workingText)) {
                        setText(workingText.substring(0,workingText.length()-1));
                    }
                }
            } catch (Exception e){
            }
        }
    }
    private Layout createWorkingLayout(String workingText) {
        int width = getWidth() - getPaddingLeft() - getPaddingRight();
        if (width == 0&&mContext!=null) {
            width = SysUtil.getScreenWidth(mContext) - Utils.dip2px(mContext, 70);
        }
        return new StaticLayout(workingText, getPaint(), width,Alignment.ALIGN_NORMAL, lineSpacingMultiplier, lineAdditionalVerticalPadding, false);
    }

    public static SpannableString getEllipsizeText(Context context,String text,int width,int maxLine,boolean readAll,boolean spoiler){
    	String ellipsis = "... ";
    	String ellipsisadd = "...";
    	if (readAll) {
    		ellipsis = "...阅读全文 ";
        	ellipsisadd = "...<Font color=#a0a0a0>阅读全文</Font>";
		}
    	if (spoiler) {
    		ellipsis = "...";
        	ellipsisadd = "....";
		}
        SpannableString workingText = TextContentTool.getSpanContent(text);
        if (maxLine != -1) {
            Layout layout = createWorkingLayout(context,workingText,width,Utils.sp2px(context,14));
            if (layout.getLineCount() > maxLine) {
                workingText = (SpannableString) workingText.subSequence(0, layout.getLineEnd(maxLine - 1));
                while (createWorkingLayout(context,workingText + ellipsis,width,Utils.sp2px(context,14)).getLineCount() > maxLine) {
                    int lastSpace = workingText.length() - 1;
                    if (lastSpace == -1 ) {
                        break;
                    }
                    workingText = (SpannableString) workingText.subSequence(0, lastSpace);
                }
                SpannableStringBuilder builder = new SpannableStringBuilder(workingText);
                builder.append(Html.fromHtml(ellipsisadd));
                return new SpannableString(builder);
            }else {
                return workingText;
            }
        }else {
            return workingText;
        }
    }
    
    private static Layout createWorkingLayout(Context context,CharSequence workingText,int width,int textSize) {
    	TextPaint   mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    	mTextPaint.density = context.getResources().getDisplayMetrics().density;
    	mTextPaint.setTextScaleX(1.0f);
    	mTextPaint.setTextSize(textSize);
        return new StaticLayout(workingText, mTextPaint, width,
                Alignment.ALIGN_NORMAL, 1.4f, 0.0f, false);
    }

    public static void setText(final Context context, final String content, final TextView textView){
        final int width = textView.getWidth();
        if (width == 0){
            textView.post(new Runnable() {
                @Override
                public void run() {
                    textView.setText(getEllipsizeText(context,content,textView.getWidth(),getDefaultMaxLine(textView),true,false));
                }
            });
        }else {
            textView.setText(getEllipsizeText(context,content,width,getDefaultMaxLine(textView),true,false));
        }
    }

    private static int getDefaultMaxLine(TextView textView){
        if(Build.VERSION.SDK_INT >= 16) {
            int lineHeight =textView.getLineHeight();
            if (lineHeight != 0) {
                return textView.getHeight()/lineHeight;
            }
            return 5;
        } else {
            return 5;
        }
    }
}
